/*
  学习目标：评论列表-子传父
*/

import React from 'react';
import './index.css';

export default class App extends React.Component {
  state = {
    username: '',
    content: '',

    list: [
      {
        id: 1,
        username: '思聪',
        content: '想你的夜',
      },
      {
        id: 2,
        username: '马芸',
        content: '我对钱不感兴趣',
      },
      {
        id: 3,
        username: '王简林',
        content: '实现一个小目标',
      },
    ],
  };

  // 1. 改造箭头函数：在父组件内定义一个函数的函数
  handleDelById = (id) => {
    const list = this.state.list.filter((item) => item.id !== id);
    this.setState({ list });
  };

  handleChange = (e) => {
    const { name, value } = e.target;
    this.setState({ [name]: value });
  };

  handleAdd = (e) => {
    e.preventDefault();

    const { username, content, list } = this.state;
    if (!username.trim() || !content.trim()) {
      alert('评论人，或评论内容不能为空');
      return;
    }

    const newObj = { username, content, id: Date.now() };
    this.setState({ list: [newObj, ...list], username: '', content: '' });
  };

  handleClear = () => {
    this.setState({ list: [] });
  };

  render() {
    const { list, username, content } = this.state;
    return (
      <div className="app">
        <form onSubmit={this.handlePublish}>
          <input
            className="user"
            type="text"
            placeholder="请输入评论人"
            value={username}
            onChange={this.handleChange}
            name="username"
          />
          <br />
          <textarea
            value={content}
            className="content"
            cols="30"
            rows="10"
            placeholder="请输入评论内容"
            name="content"
            onChange={this.handleChange}
          />
          <br />
          <button onClick={this.handleAdd}>发表评论</button>
          <button onClick={this.handleClear} type="button">
            清空评论
          </button>
        </form>
        {!list.length ? (
          <div>暂无数据</div>
        ) : (
          <CommentList
            list={list}
            // 2. 🔔传递删除的函数给子组件
            handleDelById={this.handleDelById}
          ></CommentList>
        )}
      </div>
    );
  }
}

function CommentList({ list, handleDelById }) {
  console.log('handleDelById  ----->  ', handleDelById);
  return (
    <ul>
      {list.map((item) => (
        <li key={item.id}>
          <h3>评论人: {item.username}</h3>
          <p>评论内容：{item.content}</p>
          <button
            // 3. 🔔子组件内用调用props传来的函数
            onClick={() => handleDelById(item.id)}
          >
            删除
          </button>
        </li>
      ))}
    </ul>
  );
}
